package com.menu.Utils;

import com.menu.Configuration.UploadConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件工具类
 */
@Component
@Slf4j
public class FileUtils {


    private final static String ROOT = System.getProperty("user.dir");
    //上传头像
    private final static String UPLOAD_HEADPHOTO = "/Static/user/headphoto/";
    //上传商品
    private final static  String UPLOAD_GOODS = "/Static/goods/";
    //上传菜谱制作步骤
    private final static String UPLOAD_MENU = "/Static/user/menu/";
    //上传菜单
    private final static String UPLOAD_MENU_FATHER="/Static/user/menuFather/";
    //用户上传反馈图片
    private final static  String UPLOAD_MESSAGE = "/Static/user/message/";
    //用户上传步骤图片
    private final static  String UPLOAD_STEP = "/Static/user/step/";
    //用户上传背景图片
    private final static  String UPLOAD_BACKGROUND = "/Static/user/background/";

    private final static Integer MAX_SIZE = 1024 * 1024 * 20;

    private String imgeArray [] = {"gif","jfif","jpe","jpeg","jpg","png","tif","ico"};


    /**
     * 上传头像
     * @return
     */
    public ResponseResult uploadHeadPhoto(MultipartFile multipartFile,Integer id){
        String[] path = buildFileName(0,id,multipartFile);
        return upload(multipartFile,path[0]);
    }

    /**
     * 上传商品图
     * @param multipartFile
     * @return
     */
    public ResponseResult uploadGoods(MultipartFile multipartFile,Integer id){
        String []path = buildFileName(1,id,multipartFile);
        return upload(multipartFile,path[0]);
    }

    /**
     * 上传菜单封面
     * @param multipartFile
     * @return
     */
    public ResponseResult uploadMenuFather(MultipartFile multipartFile,Integer id){
        String []path = buildFileName(3,id,multipartFile);
        return upload(multipartFile,path[0]);
    }

    /**
     * 上传食谱封面
     * @param multipartFiles
     * @param id
     * @return
     */
    public ResponseResult uploadMenu(MultipartFile multipartFiles,Integer id){
        String []path = buildFileName(2,id,multipartFiles);
        return upload(multipartFiles,path[0]);
    }

    public ResponseResult uploadMessage(Integer id,MultipartFile ...multipartFiles){
        String []path = buildFileName(4,id,multipartFiles);
        return upload(multipartFiles,path);
    }
    public ResponseResult uploadStep(MultipartFile multipartFiles,Integer id){
        String []path = buildFileName(5,id,multipartFiles);
        return upload(multipartFiles,path[0]);
    }
    public ResponseResult uploadBackGround(MultipartFile multipartFiles,Integer id){
        String []path = buildFileName(6,id,multipartFiles);
        return upload(multipartFiles,path[0]);
    }

    /**0 头像 1 商品 2 菜谱 3菜单 4反馈图片 5步骤图片 6背景图片
     * 生成文件名
     * @param multipartFiles
     * @return
     */
    private String[] buildFileName(int state,Integer id,MultipartFile ...multipartFiles){
        String [] fileNames = new String[multipartFiles.length];
        for (int i = 0; i < multipartFiles.length; i++) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(ROOT);
            switch (state){
                case 0 :
                    stringBuilder.append(UPLOAD_HEADPHOTO);
                    break;
                case 1 :
                    stringBuilder.append(UPLOAD_GOODS);
                    break;
                case 2 :
                    stringBuilder.append(UPLOAD_MENU);
                    break;
                case 3:
                    stringBuilder.append(UPLOAD_MENU_FATHER);
                    break;
                case 4:
                    stringBuilder.append(UPLOAD_MESSAGE);
                    break;
                case 5:
                    stringBuilder.append(UPLOAD_STEP);
                    break;
                default:
                    stringBuilder.append(UPLOAD_BACKGROUND);
            }
            stringBuilder.append(id.toString()+"/");
            File file = new File(stringBuilder.toString());
            if (!file.exists()){
                file.mkdirs();
            }
            stringBuilder.append(UUID.randomUUID());
            String tempFile =  multipartFiles[i].getOriginalFilename();
            stringBuilder.append(tempFile.substring(tempFile.lastIndexOf(".")));
            fileNames[i] = stringBuilder.toString();
        }
        return fileNames;
    }

    /**
     * 多文件上传
     * @param multipartFile
     * @param path
     * @return
     */
    private ResponseResult upload(MultipartFile []multipartFile,String []path){
            if (!isImg(multipartFile)){
                return ResponseResult.error("文件类型有误！");
            }
            if (!verifySize(multipartFile)){
                return ResponseResult.error("图片单张最大为5MB！");
            }
            try {
                for (int i = 0; i < multipartFile.length; i++) {
                     multipartFile[i].transferTo(new File(path[i]));
                     StringBuilder stringBuilder = new StringBuilder(UploadConfig.URL);
                     stringBuilder.append(path[i].substring(ROOT.length()));
                     path[i] = stringBuilder.toString();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
                log.info("上传失败！");
                ResponseResult.error("系统异常，文件上传失败！");
            }
        return ResponseResult.success("上传成功！", path);
    }

    private ResponseResult upload(MultipartFile multipartFile,String path){
        if (!isImg(multipartFile)){
            return ResponseResult.error("文件类型有误！");
        }
        if (!verifySize(multipartFile)){
            return ResponseResult.error("图片单张最大为5MB！");
        }
        try {
            multipartFile.transferTo(new File(path));
            StringBuilder stringBuilder = new StringBuilder(UploadConfig.URL);
            stringBuilder.append(path.substring(ROOT.length()));
            path = stringBuilder.toString();
        } catch (IOException exception) {
            exception.printStackTrace();
            log.info("上传失败！");
            ResponseResult.error("系统异常，文件上传失败！");
        }
        return ResponseResult.success("上传成功！",path);
    }


    /**
     * 判断大小
     * @param multipartFile
     * @return
     */
    private boolean verifySize(MultipartFile ...multipartFile){
        for (MultipartFile file:
             multipartFile) {
            if (file.getSize() > MAX_SIZE){
                return false;
            }
        }
        return true;
    }


    /**
     * 判断是否是图片
     * @param multipartFile
     * @return
     */
    private boolean isImg(MultipartFile ...multipartFile){
        if (multipartFile == null){
            return false;
        }
        for (int i = 0; i < multipartFile.length; i++) {
            MultipartFile file = multipartFile[i];
            if (file == null){
                return false;
            }
            String fileName = file.getOriginalFilename();
            fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
            boolean flag = false;
            for(int j = 0; j < imgeArray.length; j++){
                if (fileName.equals(imgeArray[j])){
                    flag = true;
                    continue;
                }
            }
            if (!flag){
                return false;
            }
        }
        return true;
    }

    /**
     * 删除图片
     * @param imgeArray
     */
    public void deleteFile (String ...imgeArray){
        for (String fileName:
             imgeArray) {
            StringBuilder stringBuilder = new StringBuilder(ROOT);
            stringBuilder.append(fileName.substring(UploadConfig.URL.length()));
            File file = new File(stringBuilder.toString());
            if (file.exists()){
                boolean flag = file.delete();
                if (!flag){
                    log.info("{}删除失败！",stringBuilder.toString());
                }
            }else{
                log.info("{}文件不存在！",stringBuilder.toString());
            }
        }
    }
}
